/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.epos.datalogic.define.dao;

import cn.ekuma.data.dao.ModifiedLogDAO;
import cn.ekuma.epos.db.table.I_Product;
import cn.ekuma.util.JsonUtil;

import com.openbravo.bean.AttributeSet;
import com.openbravo.bean.Product;
import com.openbravo.bean.ProductCategory;
import com.openbravo.bean.TaxCategory;
import com.openbravo.beans.DateUtils;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.DataParams;
import com.openbravo.data.loader.DataRead;
import com.openbravo.data.loader.DataWrite;
import com.openbravo.data.loader.Datas;
import com.openbravo.data.loader.I_Session;
import com.openbravo.data.loader.ImageUtils;
import com.openbravo.data.loader.PreparedSentence;
import com.openbravo.data.loader.QBFBuilder;
import com.openbravo.data.loader.SerializerReadBytes;
import com.openbravo.data.loader.SerializerWriteBasic;
import com.openbravo.data.loader.SerializerWriteParams;
import com.openbravo.data.loader.SerializerWriteString;
import com.openbravo.data.loader.Session;
import com.openbravo.data.loader.StaticSentence;
import com.openbravo.data.loader.TableDefinition;
import com.openbravo.data.model.Field;
import com.openbravo.format.Formats;
import com.openbravo.pos.bean.ProductCategoryExt;
import com.openbravo.pos.bean.ProductExt;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class ProductExtDAO extends ModifiedLogDAO<ProductExt>{
    public ProductExtDAO(I_Session s) {
        super(s);
    }


    @Override
    public TableDefinition getTable() {
        return new TableDefinition(s,
                   "PRODUCTS",
                    new Field[]{
                new Field("ID", Datas.STRING, Formats.STRING),
                new Field("REFERENCE", Datas.STRING, Formats.STRING, true, true, true),
                new Field("CODE", Datas.STRING, Formats.STRING, false, true, true),
                new Field("NAME", Datas.STRING, Formats.STRING, true, true, true),
                new Field("ISCOM", Datas.BOOLEAN, Formats.BOOLEAN),
                
                new Field("ISSCALE", Datas.BOOLEAN, Formats.BOOLEAN),
                new Field("PRICEBUY", Datas.DOUBLE, Formats.CURRENCY, false, true, true),
                new Field("PRICESELL", Datas.DOUBLE, Formats.CURRENCY, false, true, true),
                new Field("TAXCAT", Datas.STRING, Formats.STRING, TaxCategory.class),
                new Field("CATEGORY", Datas.STRING, Formats.STRING,ProductCategory.class),
                
                new Field("ATTRIBUTESET_ID", Datas.STRING, Formats.STRING, AttributeSet.class),
                new Field("IMAGE", Datas.IMAGE, Formats.NULL),
                new Field("STOCKCOST", Datas.DOUBLE, Formats.CURRENCY),
                new Field("STOCKVOLUME", Datas.DOUBLE, Formats.DOUBLE),
                new Field("ISCATALOG", Datas.BOOLEAN, Formats.BOOLEAN),
                
                new Field("CATORDER", Datas.INT, Formats.INT),
                new Field("ATTRIBUTES", Datas.STRING, Formats.STRING),
                new Field("CUSTOMERPRICESELL", Datas.DOUBLE, Formats.CURRENCY),
                new Field("ORIGIN", Datas.STRING, Formats.STRING),
                new Field("QUANTITY", Datas.DOUBLE, Formats.DOUBLE),
                
                new Field("UNIT", Datas.STRING, Formats.STRING),
                new Field("MANUFACTUR", Datas.STRING, Formats.STRING),
                new Field("SIMILARCODE", Datas.STRING, Formats.STRING),
                new Field("DURABILITY", Datas.INT, Formats.INT),
                new Field("MNEMONIC", Datas.STRING, Formats.STRING),
                
                new Field("LASTMODIFIED",Datas.TIMESTAMP, Formats.TIMESTAMP),
                new Field(I_Product.MANUFACTURING, Datas.BOOLEAN, Formats.BOOLEAN),
                new Field(I_Product.WHOLESALEPRICE, Datas.DOUBLE,
						Formats.CURRENCY),
				new Field(I_Product.CURDATE, Datas.TIMESTAMP, Formats.TIMESTAMP),
				new Field(I_Product.WEIGHT, Datas.DOUBLE, Formats.DOUBLE),
				new Field(I_Product.ISBOMSTORE, Datas.BOOLEAN, Formats.BOOLEAN),
				new Field(I_Product.SPECIFICATION, Datas.STRING, Formats.STRING)
                },
                new int[]{0}
              );
    }

    @Override
    public void writeInsertValues(DataWrite dp, ProductExt obj) throws BasicException {
          dp.setString(1,obj.getID());
          dp.setString(2, obj.getReference());
          dp.setString(3,obj.getCode());
          dp.setString(4, obj.getName());
          dp.setBoolean(5,obj.isCom());
          
          dp.setBoolean(6, obj.isScale());
          dp.setDouble(7,obj.getPriceBuy());
          dp.setDouble(8,obj.getPriceSell());
          dp.setString(9,obj.getTaxCategoryID());
          dp.setString(10,obj.getCategoryID());
          
          dp.setString(11,obj.getAttributeSetID());
          dp.setBytes(12,obj.getImage());
          dp.setDouble(13,obj.getStockCost());
          dp.setDouble(14,obj.getStockVolume());
          dp.setBoolean(15,obj.isCatalog());
          
          dp.setInt(16,obj.getCatorder());
          dp.setString(17, JsonUtil.toString(obj.getProperties()));
          dp.setDouble(18,obj.getM_dCustomerPrice());
          dp.setString(19,obj.getM_origin());
          dp.setDouble(20, obj.getM_quantity());
          
          dp.setString(21,obj.getM_unit());
          dp.setString(22,obj.getM_sManufacturer());
          dp.setString(23,obj.getM_sSimilarCode());
          dp.setInt(24,obj.getM_iDurability());
          dp.setString(25,obj.getMnemonic());
          
          dp.setTimestamp(26, obj.getLastModified());
          dp.setBoolean(27,obj.isM_bManufacturing());
          dp.setDouble(28,obj.getM_dWholesalePrice());
          dp.setTimestamp(29,obj.getCurDate());
          dp.setDouble(30,obj.getWeight());
          dp.setBoolean(31,obj.isBomStore());
          dp.setString(32,obj.getSpecification());
    }

    public ProductExt readValues(DataRead dr,ProductExt product) throws BasicException {
            if(product==null)
            	product = new ProductExt();
            product.setID(dr.getString(1));
            product.setReference( dr.getString(2));
            product.setCode(dr.getString(3));
            product.setName( dr.getString(4));
            product.setCom(dr.getBoolean(5).booleanValue());
            
            product.setScale( dr.getBoolean(6).booleanValue());
            product.setPriceBuy(dr.getDouble(7).doubleValue());
            product.setPriceSell( dr.getDouble(8).doubleValue());
            product.setTaxCategoryID(dr.getString(9));
            product.setCategoryID(dr.getString(10));
            
            product.setAttributeSetID( dr.getString(11));
            product.setImage(dr.getBytes(12));
            product.setStockCost(dr.getDouble(13));
            product.setStockVolume(dr.getDouble(14));
            product.setCatalog(dr.getBoolean(15));
            
            product.setCatorder(dr.getInt(16));
            product.setAttributes(JsonUtil.getHashMap(dr.getString(17)));
            product.setM_dCustomerPrice(dr.getDouble(18));
            product.setM_origin(dr.getString(19));
            product.setM_quantity(dr.getDouble(20));
            
            product.setM_unit(dr.getString(21));
            product.setM_sManufacturer(dr.getString(22));
            product.setM_sSimilarCode(dr.getString(23));
            product.setM_iDurability(dr.getInt(24));
            product.setMnemonic(dr.getString(25));
            
            product.setLastModified(dr.getTimestamp(26));
            product.setM_bManufacturing(dr.getBoolean(27));
            product.setM_dWholesalePrice(dr.getDouble(28));
            product.setCurDate(dr.getTimestamp(29));
            product.setWeight(dr.getDouble(30));
            product.setBomStore(dr.getBoolean(31));
            product.setSpecification(dr.getString(32));
            return product;
    }

    @Override
    public List<ProductExt> list(Object filter) throws BasicException {
        return new StaticSentence(s, new QBFBuilder(
                this.getTableDefinition().getListSQL()+" WHERE ?(QBF_FILTER) "
                + "ORDER BY REFERENCE", new String[]{"NAME", "PRICEBUY", "PRICESELL", "CATEGORY", "CODE"}), new SerializerWriteBasic(new Datas[]{Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.DOUBLE, Datas.OBJECT, Datas.STRING, Datas.OBJECT, Datas.STRING}), this).list(filter);
    }

    public Class getSuportClass() {
        return ProductExt.class;
    }

    public List<ProductExt> getProductCatalog(String category) throws BasicException {
        return new PreparedSentence(s,getTableDefinition().getListSQL()+" WHERE CATEGORY = ? AND ISCATALOG="+s.getDB().TRUE() + " "
                + "ORDER BY CATORDER, NAME", SerializerWriteString.INSTANCE, this).list(category);
    }

    public List<ProductExt> getProductComments(String id) throws BasicException {
        return new PreparedSentence(s, getTableDefinition().getListSQL("P")+",  PRODUCTS_COM M WHERE  P.ID = M.PRODUCT2 AND M.PRODUCT = ? "
                + "AND P.ISCATALOG="+s.getDB().TRUE() + " "
                + "AND P.ISCOM = " + s.getDB().TRUE() + " "
                + "ORDER BY P.CATORDER, P.NAME", SerializerWriteString.INSTANCE, this).list(id);
    }
    
    @Override
	public Class transClass(Class in) {
		if (in == ProductCategoryExt.class)
			return ProductCategory.class;
		return super.transClass(in);
	}
    
    public byte[] findProductImage(String productId)throws BasicException{
    	 return (byte[]) new StaticSentence(s,"SELECT IMAGE FROM PRODUCTS WHERE ID=?", SerializerWriteString.INSTANCE,SerializerReadBytes.INSTANCE ).find(productId); 
    }
    
    public List<ProductExt> getPrefPriceProductExt() throws BasicException {
        return new PreparedSentence(s, getTableDefinition().getListSQL("P")+",  PRODUCTPREFPRICE M WHERE  P.ID = M.ID  "
                + "ORDER BY P.NAME", null, this).list();
    } 
    
    public final List<ProductExt> getBomProductForIncludeListById(String productId)
	throws BasicException {
        return new PreparedSentence(s, this.getTableDefinition()
		.getListSQL("P") + ", BOMS B WHERE B.PARENT=P.ID AND B.REFID=?",
		SerializerWriteString.INSTANCE, this).list(productId);
   }
	
   public List<ProductExt> getNewProducts()throws BasicException{
	   return new PreparedSentence(s,getTableDefinition().getListSQL()+" WHERE CURDATE > ? AND ISCATALOG="+s.getDB().TRUE() + " "
               + "ORDER BY CATORDER, NAME", SerializerWriteParams.INSTANCE, this).list(new DataParams(){
            	   public void writeValues() throws BasicException {
            		   setTimestamp(1,DateUtils.getToday());
               }
               });
    }
   
   public List<ProductExt> listPosShardProducts()throws BasicException{
	   return new PreparedSentence(s,getTableDefinition().getListSQL("P")+",POSSHAREDPRODUCTS S WHERE P.ID=S.PRODUCT ORDER BY S.KEYSTOKE", null, this).list();
    }


public void saveProductImage(final String id, final byte[] m_ImageDatas) throws BasicException {
	new PreparedSentence(s,"UPDATE  PRODUCTS SET IMAGE=? WHERE ID=?", SerializerWriteParams.INSTANCE,null).exec(new DataParams(){
		public void writeValues() throws BasicException {
			setBytes(1, m_ImageDatas);
			setString(2, id);
		}
	});
}
}
